package com.xx.web.websocket.client;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import java.nio.ByteBuffer;

@Slf4j
@Component
@ClientEndpoint
public class MyWebSocketClient {

    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        String protobufMessage = "hello server!,连接成功";
        try {
            sendMessage(protobufMessage);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @OnMessage
    public void onMessage(byte[] message, Session session) {
        // handle received message
//        System.out.println(Arrays.toString(message));
        ByteBuffer buffer = ByteBuffer.wrap(message);
        int i = 0;
        System.out.println("start---------------------------");
        while (buffer.hasRemaining()) {
            int messageLength = buffer.getInt(); // 先读取消息长度
//            System.out.println(messageLength);
            byte[] messageBytes = new byte[messageLength];
            buffer.get(messageBytes); // 读取消息内容
            // 处理解析出来的消息
/*            try {
                ShipOuterClass.Ship ship = ShipOuterClass.Ship.parseFrom(messageBytes); // 解析消息
                System.out.println("client接收到消息: " + ++i);
                System.out.println("client ship: " + TextFormat.printToUnicodeString(ship));
            } catch (InvalidProtocolBufferException e) {
                throw new RuntimeException(e);
            }*/

        }
        System.out.println("end---------------------------");

    }
    @OnError
    public void processError(Throwable t) {
        WSClient.session = null;
        try {
            Thread.sleep(3000);
            WSClient.startWS();
        } catch (InterruptedException e) {
            log.error("---websocket processError InterruptedException---", e);
        }
        log.error("---websocket processError error---", t);
    }
    @OnClose
    public void processClose(Session session, CloseReason closeReason) {
        log.error(session.getId() + closeReason.toString());
    }
    public void sendMessage(String message) throws Exception {
        this.session.getBasicRemote().sendText(message);
    }
    public void sendMessage(byte[] message) throws Exception {
        this.session.getBasicRemote().sendBinary(ByteBuffer.wrap(message));
    }

/*    public static void main(String[] args) throws Exception {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        MyWebSocketClient client = new MyWebSocketClient();
        Session session = container.connectToServer(client, URI.create("ws://localhost:9125/wb/track"));

//        byte[] protobufMessage = createProtobufMessage();
        String protobufMessage = "hello server!";
        client.sendMessage(protobufMessage);
    }*/

/*    private static byte[] createProtobufMessage() {
        // create a protobuf message and serialize it to a byte array
        return MyProto.MyMessage.newBuilder()
                .setId(123)
                .setName("John Doe")
                .build()
                .toByteArray();
    }*/
}
